<?php
/******************************************************
v4 - Management Framework
Copyright (C) 2008  Gary Taylor, gMerc Incorporation
http://www.gmerc.com/v4/

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

gary@gmerc.com
******************************************************/
class dir_categories {
  function fetch_dir_category_parents($rootpath) {
    $arrreturn=array();
    if (!is_dir($rootpath)) { return $arrreturn; }

    if (strstr($rootpath,"/")) {
      $arrdir = explode("/",$rootpath);
      $pred='';
      foreach ($arrdir as $d) {
        array_unshift($arrreturn,$pred.$d);
        $pred.=$d.'/';
      }
    } else {
       $arrreturn=array($rootpath);
    }

    return $arrreturn;
  }

  function fetch_dir_category_children($rootpath,$all='1') {
    $arrcategories=array();
    $arrreturn=array();
    if (!is_dir($rootpath)) { return $arrreturn; }

    $dir = dir($rootpath);
    while ($file = $dir->read()) {
      if($file != "." && $file != "..") {
        if (is_dir($rootpath.$file)) {
          array_push($arrcategories,$file);
          array_push($arrreturn,$file);
        }
      }
    }
    $dir->close();

    if ($all=='1') {
      $currentprefix='';
      $lastparentid='';
      $curparentid='';

      while (!empty($arrcategories)) {

        if (!in_array($arrcategories[0],$arrreturn)) {
          array_unshift($arrreturn,$arrcategories[0]);
          $curpath=$rootpath.$arrcategories[0].'/';
          array_shift($arrcategories);

          $dir = dir($curpath);
          while ($file = $dir->read()) {
            if($file != "." && $file != "..") {
              if (is_dir($curpath.$file)) {
                array_unshift($arrcategories,$arrcategories[0].'/'.$file);
              }
            }
          }
          $dir->close();

        } else {
          array_shift($arrcategories);
        }
      }
    }

    return $arrreturn;
  }

  function get_dir_children_count($dirpath) {
    $childrencnt=0;

    if ($dirpath!='' && is_dir($dirpath)) {
      $dir = dir($dirpath);
      while ($file = $dir->read()) {
        if($file != "." && $file != "..") {
          if (is_dir($dirpath.$file)) {
            $childrencnt+=1;
          }
        }
      }
      $dir->close();
    } else {
      $childrencnt=-1;
    }

    return $childrencnt;
  }
}